package com.mall.exception;

import com.mall.common.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.util.ArrayList;
import java.util.List;

/**
 * @description 全局异常处理器
 * @author Mr.M
 * @date 2022/9/6 11:29
 * @version 1.0
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
	@ResponseBody
	@ExceptionHandler(value = MethodArgumentNotValidException.class)//ClassCastException
	public R doValidException(MethodArgumentNotValidException argumentNotValidException) {
		BindingResult bindingResult = argumentNotValidException.getBindingResult();//获取结果集合
		List<String> errors=new ArrayList<>();
		List<FieldError> fieldErrors = bindingResult.getFieldErrors();
		bindingResult.getFieldErrors().stream().forEach(item->{
			if (item.getField().equals("name")){
				errors.add("分类名称"+item.getDefaultMessage());
			}
			if (item.getField().equals("type")){
				errors.add("分类级别"+item.getDefaultMessage());
			}
		});
		StringUtils.join(errors,",");
		return  R.error(errors.toString());
	}
	@ResponseBody
	@ExceptionHandler(value = ClassCastException.class)//
	public R doCastException(ClassCastException classCastException) {
		if (classCastException.getMessage().equals("java.lang.String cannot be cast to com.mall.entity.LoginUser")){
			return  R.error("登录信息过期");
		}else {
			return R.error("未知异常");
		}

	}
}
